package org.jeecg.modules.inspection.service.impl;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.inspection.entity.Inspection;
import org.jeecg.modules.inspection.entity.InspectionUser;
import org.jeecg.modules.inspection.entity.PinspectionItem;
import org.jeecg.modules.inspection.entity.PinspetionArea;
import org.jeecg.modules.inspection.mapper.InspectionMapper;
import org.jeecg.modules.inspection.mapper.InspectionUserMapper;
import org.jeecg.modules.inspection.mapper.PinspectionItemMapper;
import org.jeecg.modules.inspection.mapper.PinspetionAreaMapper;
import org.jeecg.modules.inspection.service.IInspectionDataApiService;
import org.jeecg.modules.inspection.vo.LineAreaItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

@Slf4j
@Service
public class InspectionDataApiServiceImpl implements IInspectionDataApiService {

    @Autowired
    private InspectionUserMapper inspectionUserMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private PinspetionAreaMapper pinspetionAreaMapper;

    @Autowired
    private PinspectionItemMapper pinspectionItemMapper;

    @Override
    @Transactional
    public synchronized void generateInsTask(){
        //更新历史未巡检的记录为超时未巡状态
        Date now = new Date();
        List<String> processIds = inspectionMapper.getOutTimeList(now);
        if(processIds != null && processIds.size() > 0){
            Integer count = inspectionMapper.updateToOutTime(now);
            log.info("变更了{}条巡检线路为超时未检",count);
            if(count > 0){
                Integer countArea = pinspetionAreaMapper.updateToOutTime(processIds);
                log.info("变更了{}个巡检区域为超时未检",countArea);
            }
        }
        List<InspectionUser> userList = inspectionUserMapper.selectListForLive();
        if(userList == null || userList.size() == 0){
            log.info("需要生成巡检任务的人员列表为空，任务结束");
            return;
        }
        String dateString = DateUtils.date_sdf.format(now);
        Calendar cNow = Calendar.getInstance();
        cNow.setTime(new DateTime(now));
        Map<String, List<LineAreaItemVO>> lineItemsMap = new HashMap<>();
        for(InspectionUser user : userList){
            if(user.getNextTime() == null){
                //未初始化巡检时间，跳过生成巡检任务
                continue;
            }
            int period = user.getPeriod();
            String periodType = user.getPeriodType();
            if(period == 0 || StringUtils.isBlank(periodType)){
                continue;
            }
            String nextDateString = DateUtils.date_sdf.format(user.getNextTime());
            if(dateString.compareTo(nextDateString) >= 0 ){
                //当前日期超过或者相等触发日期，可以触发生成巡检任务
                genareteByUser(user,now,period,periodType,lineItemsMap);
            }
        }
    }

    private void genareteByUser(InspectionUser user,Date now,int period,String periodType,Map<String, List<LineAreaItemVO>> lineItemsMap) {
        log.info("lineItemsMap的长度为:"+lineItemsMap.size());
        log.info("开始生成{}的巡检任务,巡检任务生成周期为{}{}一次",user.getUserName(),period,periodType);
        //获取并更新下一次生成巡检任务的时间
        Date nextDate = DateUtils.addDate(now,period,periodType);
        if(nextDate == null){
            log.info("未识别的巡检周期类型");
            return;
        }
        inspectionUserMapper.updateNextTime(user.getId(),nextDate);

        //设置巡检主表的信息
        Inspection inspection = new Inspection();
        //inspection.setCompanyId();
        inspection.setId(UUIDGenerator.getUUID());
        inspection.setConfigLineId(user.getLineId());
        inspection.setOfficeId(user.getOfficeId());
        inspection.setType(user.getType());
        inspection.setOvertimeDate(nextDate);
        inspection.setProcessDay(now);
        inspection.setStatus(100);
        inspection.setUserId(user.getUserId());
        inspection.setTenantId(user.getTenantId());
        inspection.setCreateTime(now);
        inspection.setPeriod(period);
        inspection.setPeriodType(periodType);
        inspectionMapper.insertBatch(Collections.singletonList(inspection));
        //查询出巡检线路下的巡检项
        List<LineAreaItemVO> itemVOS;
        if(lineItemsMap.containsKey(user.getLineId())){
            itemVOS = lineItemsMap.get(user.getLineId());
        }else{
            //查询
            itemVOS = inspectionUserMapper.selectItemsList(user.getLineId());
            lineItemsMap.put(user.getLineId(),itemVOS);
        }
        if(itemVOS == null || itemVOS.size() == 0){
            return;
        }
        String cAreaId = null;
        String cProcessAreaId = null;
        List<PinspetionArea> areas = new ArrayList<>();
        List<PinspectionItem> items = new ArrayList<>();
        for(LineAreaItemVO vo : itemVOS){
            if(StringUtils.isEmpty(vo.getAreaId())){
                continue;
            }
            if(cAreaId == null || !cAreaId.equals(vo.getAreaId())){
                cAreaId = vo.getAreaId();
                PinspetionArea pArea = new PinspetionArea();
                pArea.setId(UUIDGenerator.getUUID());
                pArea.setName(vo.getAreaName());
                pArea.setProcessId(inspection.getId());//设置巡检任务主表id
                pArea.setConfigLineAreaId(vo.getAreaId());
                pArea.setStatus(100);
                pArea.setTenantId(user.getTenantId());
                pArea.setCreateTime(now);
                pArea.setOfficeId(vo.getOfficeId());
                pArea.setProjectId(vo.getProjectId());
                pArea.setFloorId(vo.getFloorId());
                pArea.setTire(vo.getTire());
                pArea.setNumber(vo.getAreaNumber());
                cProcessAreaId = pArea.getId();
                areas.add(pArea);
            }
            if(StringUtils.isEmpty(vo.getItemId()) || StringUtils.isEmpty(cProcessAreaId)){
                continue;
            }

            PinspectionItem pItem = new PinspectionItem();
            pItem.setId(UUIDGenerator.getUUID());
            pItem.setName(vo.getItemName());
            pItem.setProcessId(inspection.getId());
            pItem.setProcessAreaId(cProcessAreaId);
            pItem.setConfigItemId(vo.getItemId());
            pItem.setTenantId(user.getTenantId());
            pItem.setIsCheck(0);
            pItem.setNumber(vo.getItemNumber());
            pItem.setCreateTime(now);
            items.add(pItem);
        }
        if(areas.size() > 0){
            pinspetionAreaMapper.insertBatch(areas);
        }
        if(items.size() > 0){
            pinspectionItemMapper.insertBatch(items);
        }
    }



    public static void main(String[] args) throws ParseException {
        Date cDate = DateUtils.datetimeFormat.parse("2019-12-31 11:11:11");
        Date date = DateUtils.addDate(cDate,0,"month");
        if(date == null){
            log.info("未识别的巡检周期类型");
        }else{
            System.out.println(DateUtils.datetimeFormat.format(date));
        }
    }

}
